package spring.boot.rocketmq.receiver.config;

import lombok.extern.log4j.Log4j2;
import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.common.message.MessageExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.List;

@Configuration
@Log4j2
public abstract class TopicTestConsumerConfigure {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private RocketMQConfig rocketMQConfig;

    public void listener(String topic, String tag) throws MQClientException {
        DefaultMQPushConsumer consumer = new DefaultMQPushConsumer(rocketMQConfig.getTestGroupName());
        consumer.setNamesrvAddr(rocketMQConfig.getNamesrvAddr());
        consumer.subscribe(topic, tag);
        // 开启内部类实现监听
        consumer.registerMessageListener(new MessageListenerConcurrently() {
            @Override
            public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs, ConsumeConcurrentlyContext context) {
                return TopicTestConsumerConfigure.this.dealBody(msgs);
            }
        });
        consumer.start();
        logger.info("开启Topic:" + topic + "  Tag:" + tag + "  消费----------success---------");

    }

    // 处理body的业务
    public abstract ConsumeConcurrentlyStatus dealBody(List<MessageExt> msgs);

}